package zero.tech.games.gateway.config;

import java.util.List;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang3.StringUtils;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.Server;
public class CustomRouter extends AbstractLoadBalancerRule{

	
	@Override
	public Server choose(Object key) {
		//hint 格式 "BACKROOM###ip:port"
		String hint=(String) key;
		String hostAndPort=null;
		if(StringUtils.isNotBlank(hint)&&hint.startsWith("BACKROOM")) {
			hostAndPort=hint.split("###")[1];
		}
		Server server=null;
		if(StringUtils.isNotBlank(hostAndPort)) {
			String host=hostAndPort.split(":")[0];
			int port=Integer.valueOf(hostAndPort.split(":")[1]);
			List<Server> reachableServers=this.getLoadBalancer().getReachableServers();
			if(reachableServers.isEmpty()) {
				
			}else if(reachableServers.size()==1) {
				Server find=reachableServers.get(0);
				if(find.getHost().equals(host)&&find.getPort()==port) {
					server=find;
				}
			}else {
				for(Server find:reachableServers) {
					if(find.getHost().equals(host)&&find.getPort()==port) {
						server=find;
						break;
					}
				}
			}
		}else {
			List<Server> reachableServers=this.getLoadBalancer().getReachableServers();
			if(reachableServers.isEmpty()) {
				
			}else if(reachableServers.size()==1) {
				server=reachableServers.get(0);
			}else {
				server=randomOneReachable(reachableServers);
			}
		}
		return server;
	}

	private Server randomOneReachable(List<Server> reachableServers) {
		int index=RandomUtils.nextInt(reachableServers.size());
		return reachableServers.get(index);
	}

	@Override
	public void initWithNiwsConfig(IClientConfig clientConfig) {
		System.out.println(clientConfig);
	}

}
